package net.xdclass.coupon.message;

import lombok.extern.slf4j.Slf4j;
import net.xdclass.common.message.MessageInfo;
import net.xdclass.common.message.MessageProducer;
import net.xdclass.coupon.config.RabbitMqConfig;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.connection.PublisherCallbackChannel;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * 消息发送
 */
@Slf4j
@Component(value = "couponMessageProducer")
public class CouponMessageProducer implements MessageProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RabbitMqConfig config;

    /**
     * 发送消息
     *
     * @param messageInfo
     */
    @Override
    public void sendMsg(MessageInfo messageInfo) {
        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
        messageInfo.setMessageId(correlationId.getId());
        rabbitTemplate.convertAndSend(config.getEventExchange(), config.getCouponReleaseDelayRoutingKey(), messageInfo, correlationId);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            log.warn("消息发送到exchange成功,id: {}", correlationData.getId());
        } else {
            log.warn("消息发送到exchange失败,原因: {}", cause);
        }
    }

    @Override
    public void returnedMessage(org.springframework.amqp.core.Message message, int replyCode, String replyText, String exchange, String routingKey) {
        String correlationId = message.getMessageProperties()
                .getHeader(PublisherCallbackChannel.RETURNED_MESSAGE_CORRELATION_KEY);
        log.warn("消息：{} 发送成功, 应答码：{} 原因：{} 交换机: {}  路由键: {}", correlationId,
                replyCode, replyText, exchange, routingKey);
    }
}
